'use strict';

const Service = require('egg').Service;

class UserService extends Service {
  async getList({ name = '', page = 1, limit = 20 }) {
    const { Op } = this.app.Sequelize;
    const where = {};
    if (name) {
      where.name = {
        [Op.like]: `%${name}%`,
      };
    }
    const users = await this.ctx.model.User.findAndCountAll({
      where,
      offset: (page - 1) * limit,
      limit,
      order: [
        [ 'id', 'DESC' ],
      ],
    });
    return users;
  }

  async create(userInfo) {
    const user = await this.ctx.model.User.create(userInfo);
    return user;
  }

  async update({ id, name, addr, age, birth, sex }) {
    const updateRes = await this.ctx.model.User.update(
      {
        name,
        addr,
        age,
        birth,
        sex,
      },
      {
        where: {
          id,
        },
      }
    );
    return updateRes && updateRes[0] > 0;
  }

  async delete(id) {
    const deleteRes = await this.ctx.model.User.destroy({
      where: {
        id,
      },
    });
    return deleteRes > 0;
  }
}

module.exports = UserService;
